﻿using System;
using System.Collections.Generic;
using System.Text;
using Barbar.MapReport.Common.Drawing;
using System.Web.Services;
using Barbar.MapReport.HtmlRender.Resources;
using Barbar.MapReport.HtmlRender.Handlers;
using Barbar.MapReport.Common.Drawing.Commands;

namespace Barbar.MapReport.HtmlRender {
  public class RenderingService : RenderingServiceBase {
    Queue<DrawingCommand> m_CommandQueue = new Queue<DrawingCommand>();

    public MapHtmlFragment Render(RenderSettings settings) {
      RenderingContext context = new RenderingContext(settings.MapProxyUrl, settings.MapObjectName);
      Renderer renderer = new Renderer(context);
      while (m_CommandQueue.Count > 0) {
        DrawingCommand command = m_CommandQueue.Dequeue();
        command.Render(renderer);
      }
      ReplacementTemplate template = settings.CreateTemplate();
      template.AddMessage("ScriptUrl", HandlerUrl.GetResourceUrl("Barbar.MapReport.HtmlRender.Resources.Script.js").ToString(settings.MapProxyUrl));
      template.AddMessage("Code", context.Content);
      template.AddMessage("LNGNotFound", Translator.LNGNotFound);
      template.AddMessage("LNGGoogleServerNotFound", Translator.LNGGoogleServerNotFound);
      template.AddMessage("LNGSearch", Translator.LNGSearch);
      template.AddMessage("LoadingImage", HandlerUrl.GetResourceUrl("Barbar.MapReport.HtmlRender.Resources.Loading.gif").ToString(settings.MapProxyUrl));

      MapHtmlFragment fragment = new MapHtmlFragment();
      fragment.MapElement = template.ApplyTo(Utility.GetEmbeddedResource("MapHtmlFragment.htm", true));
      foreach (string legendElement in context.LegendElements)
        fragment.LegendElements.Add(legendElement);
      return fragment;
    }

    #region IRenderingService Members

    protected override void ExecuteInternal(DrawingCommand command) {
      if (command == null)
        throw new ArgumentNullException("command");
      m_CommandQueue.Enqueue(command);
    }

    #endregion
  }
}
